package com.atguigu.flink03;

import com.atguigu.beans.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/2/20
 * 该案例演示了flatmap算子
 * 如果输入的数据是sensor_1，只打印vc；如果输入的数据是sensor_2，既打印ts又打印vc。
 */
public class Flink10_Trans_FlatMap {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<WaterSensor> stream = env.fromElements(
                new WaterSensor("sensor_1", 1L, 1),
                new WaterSensor("sensor_1", 2L, 2),
                new WaterSensor("sensor_2", 2L, 2),
                new WaterSensor("sensor_3", 3L, 3)
        );

       stream.flatMap(
               new FlatMapFunction<WaterSensor, String>() {
                   @Override
                   public void flatMap(WaterSensor ws, Collector<String> out) throws Exception {
                       if("sensor_1".equals(ws.id)){
                           out.collect(ws.id + ":::" + ws.vc);
                       }else if ("sensor_2".equals(ws.id)){
                           out.collect(ws.id + ":::" + ws.vc);
                           out.collect(ws.id + ":::" + ws.ts);
                       }
                   }
               }
       ).print();

        env.execute();
    }
}
